<?php
class Lead_EDO_Datatype_Field_Relation_HasAndBelongsToMany
{
    
    public static function getJoinTable($field)
    {
        if($joinTable = $field->getConfig('join_table'))
            return $joinTable;
        
        $sortArr = array($field->getOwner()->getClass(), $field->getRelatedClass());
        sort($sortArr);
        
        if(array_shift($sortArr) == $field->getOwner()->getClass()) {
            $joinTable = $field->getOwner()->getClass() . '_' . $field->getName() . '_' . $field->getRelatedClass() . '_' . $field->getForeignKey();
        } else {
            $joinTable = $field->getRelatedClass() . '_' . $field->getForeignKey() . '_' . $field->getOwner()->getClass() . '_' . $field->getName();
        }
        $joinTable = strtolower($joinTable);
        
        return $joinTable;        
    }
    
    
    
    public static function getValue($field)
    {
        $joinTable = self::getJoinTable($field);
		$obj = $field->getOwner()->getHandler()->get($field->getRelatedClass());
		
		$finder = $obj->getFinder();
				
		$finder->addJoin($joinTable, 'INNER', strtolower($field->getOwner()->getClass()) . "_id = {$field->getOwner()->id} AND " . strtolower($field->getRelatedClass()) . "_id = edo.id");
		
		if($field->getConfig('order'))
		    $finder->addOrderer($field->getConfig('order'));
				    
		return $finder->findAll();
    }
    
    
    public static function isNotNull()
    {
        return false;
    }
    
    
}